package ttt;
import java.util.Arrays;

public class BoardEvaluator {
	
	public static final int STATUS_X_WINS = 1;
	public static final int STATUS_O_WINS = -1;
	public static final int STATUS_TIE = 0;
	public static final int STATUS_UNDEFIND = -2;
	
	private int verWin(int[] board) {
		for(int i = 0; i < 3; i++) {
			boolean win = board[0 + i] == board[3 + i] && 
							board[3 + i] == board[6 + i] && board[3 + i] != TicTacToe.EMPTY_MARK;
			
			if(win)
				return board[i];
		}
		
		return STATUS_UNDEFIND;
	}
	
	private int horWin(int[] board) {
		for(int i = 0; i < 3; i++) {
			boolean win = board[0 + 3*i] == board[1 + 3*i] && 
							board[1 + 3*i] == board[2 + 3*i] && board[1 + 3*i] != TicTacToe.EMPTY_MARK;
			
			if(win)
				return board[3*i];
		}
		
		return STATUS_UNDEFIND;
	}
	
	private int diaWin(int[] board) {
		for(int i = 0; i <= 2; i = i + 2) {
			boolean win = board[0 + i] == board[4] && board[4] == board[8 - i] && board[4] != TicTacToe.EMPTY_MARK;
		
			if(win)
				return board[i];
		}
		
		return STATUS_UNDEFIND;		
	}
	
	public int[][] toBoard(int[] board) {
		int[][] newBoard = new int[3][3];
		for(int i = 0; i < 9; i++) {
			Point p = Point.indexToPoint(i);
			newBoard[p.getRow()][p.getColumn()] = board[i];
		}
		
		return newBoard;
	}
	
	public int[] toArray(int[][] board) {
		int[] boardArray = new int[9];
		int k = 0;
		
		for(int i = 0; i < 3; i++) {
			for(int j = 0; j < 3; j++) {
				boardArray[k] = board[i][j];
				k++;
			}
		}
		
		return boardArray;
	}
	
	public boolean equalsByRotation(int[] constArray, int[] rotArray) {
		if(Arrays.equals(constArray, rotArray))
			return true;
			
		String index = "258147036";
	
		for(int k = 0; k < 3; k++) {
			int[] rotated = new int[rotArray.length];
			for(int i = 0; i < rotArray.length; i++) {
				int j = Character.getNumericValue(index.charAt(i));
				rotated[j] = rotArray[i];
			}
			
			if(Arrays.equals(constArray, rotated))
				return true;
			else
				rotArray = rotated;
		}
		
		return false;
	}
	
	public int status(int[] board) {
		int state;
		if((state = verWin(board)) != STATUS_UNDEFIND || (state = horWin(board)) != STATUS_UNDEFIND || (state = diaWin(board)) != STATUS_UNDEFIND)
			return state;
		
		for(int i = 0; i < 9; i++)
			if(board[i] == 0)
				return STATUS_UNDEFIND;
		
		return STATUS_TIE;
	}
	
	public boolean isOccupied(int[] board, int index) {
		Point p = Point.indexToPoint(index);
		return isOccupied(board, p.getRow(), p.getColumn());
	}
	
	public boolean isOccupied(int[] board, int row, int col) {
		return isOccupied(toBoard(board), row, col);
	}
	
	public boolean isOccupied(int[][] board, int row, int col) {
		return !(board[row][col] == TicTacToe.EMPTY_MARK);
	}
	
	public int status(int[][] board) {
		int[] a = toArray(board);
		return status(a);
	}
}
